<?php
namespace App\GraphQL\Mutations\Client;

use App\Models\Wechat;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class WeChatLogin
{
    use LoginTrait;

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $miniProgram = \EasyWeChat::miniProgram('client');
        $miniProgramSession = $miniProgram->auth->session($args['code']);
        $openid = $miniProgramSession['openid'];
        $sessionkey = $miniProgramSession['session_key'];
        $wechat = Wechat::where('open_id', $openid)->first();
        if (! $wechat) {
            $data = [
                'role' => 'MEMBER',
                'open_id' => $openid,
                'password' => bcrypt($openid),
                'session_key'=>$sessionkey
            ];
            $wechat = Wechat::create($data);
        } else{
            $wechat->session_key = $sessionkey;
            $wechat->save();
        }
        $credentials = $this->buildCredentials([
            'username' => $wechat->open_id,
            'password' => $wechat->open_id
        ]);
        $response = $this->makeRequest($credentials);
        $response['wechat'] = $wechat;
        return $response;
    }
}
